<template>
  <div class="modal">
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <div class="loginbox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 切换导航 -->
      <section class="nav">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号登录</a
        >
        <span>|</span>
        <a href="#" :class="{ active: !isShowContent }" @click="showQrCode"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <div class="phonelogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
            <!-- <input type="text" placeholder="" class="ipt" /> -->
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              class="ipt"
              v-model="code"
            />
            <!-- <button -->
            <!-- class="btncode btn" -->
            <!-- @click="getCode" -->
            <!-- :disabled="isShowCount ? true : false" -->
            <!-- > -->
            <!-- {{ isShowCount ? `${count}秒` : "获取验证码" }} -->
            <!-- </button> -->
            <button class="btncode btn" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btncode btn" v-show="isShowCount">
              {{ `${count}s` }}
            </button>
          </div>
          <div class="row">
            <button class="btnlogin btn" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信登录   加个id weixin -->
        <div id="weixin" class="qrlogin" v-show="!isShowContent">
          微信扫码登录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import { BindPhoneAPI } from "@/request/api";
import { validatePhoneNumber } from "@/utils";
import { SendSMSAPI } from "@/request/api";
import { PhoneLoginAPI } from "@/request/api";
import { UserProfilesAPI } from "@/request/api";
export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      phoneNumber: "",
      // 倒计时
      count: 5,
      isShowCount: false,
      code: "",
    };
  },
  methods: {
    // 获取微信二维码
    showQrCode() {
      this.isShowContent = false;
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0K",
      });
    },
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogin: "loginStatus/changeIsLogin",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    countdown() {
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--; //递减
        if (this.count == 0) {
          clearInterval(timer);
          this.isShowCount = false;
          this.count = 5;
        }
      }, 1000);
    },
    toVerity() {
      if (!validatePhoneNumber(this.phoneNumber)) {
        this.asyncIsShowToast({
          msg: "请输入正确的手机号",
          type: "danger",
        });
        return false;
      }
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        this.asyncIsShowToast({
          msg: "请进行滑块验证",
          type: "danger",
        });
        return false;
      }

      return true;
    },
    async getCode() {
      // 1 手机号输入正确, 不正确   return
      // let reg =
      // /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      // console.log(reg.test(this.phoneNumber));
      // if (!validatePhoneNumber(this.phoneNumber)) {
      // alert("请输入正确的手机号");
      // return;
      // }

      // 2 滑动验证码正确, 不正确   return
      // 如果是向右滑动  或者失再试一次  都是表示不成功
      // if (this.msg == "向右滑动" || this.msg == "再试一次") {
      // alert("请进行滑块验证");
      // return;
      // }
      // let flag = this.toVerity();
      // if (!flag) return;
      if (!this.toVerity()) return;

      // 3 获取验证码功能(给后台发起一个请求),发送成功后倒计时
      // 倒计时
      let res = await SendSMSAPI({
        phone: this.phoneNumber.trim(),
      });
      if (!res) return;
      // console.log("发送请求结果", res);
      if (res.code == 0 || res.code == 400) {
        alert("短信验证码发送成功");
        this.countdown();
      }
    },
    async submitFn() {
      // 1 手机号输入正确, 不正确   return
      // 2 滑动验证码正确, 不正确   return
      // 3 获取验证码功能(给后台发起一个请求),发送成功后倒计时
      if (!this.toVerity()) return;

      if (this.code.trim() === "") {
        alert("请输入验证码！");
        return;
      }

      // 4 发起登录请求
      // 分场景
      // 是否有uuid
      let uuid = localStorage.getItem("uuid");
      let res;
      if (uuid) {
        res = await BindPhoneAPI({
          verifyCode: this.code.trim(),
          phone: this.phoneNumber.trim(),
          uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          verifyCode: this.code.trim(),
          phone: this.phoneNumber.trim(),
        });
      }

      if (!res) return;
      console.log(res);
      alert("登录成功");
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      this.changeIsShowLoginModal(false);
      this.changeIsLogin(true);
      uuid && localStorage.removeItem("uuid");
      this.$router.push(this.$route.path);
      // 获取用户信息
      this.asyncChangeUserInfo();
      // let res2 = UserProfilesAPI();
      // console.log(res2);
      // console.log(1111);
      // this.changeIsShowToast({
      //是否显示提示
      // isShow: true,
      //显示内容
      // msg: "你已经登录成功了",
      //提示图标类型
      // type: "success",
      // });
      // setTimeout(() => {
      // this.changeIsShowToast({
      // isShow: false,
      // });
      // }, 1500);
    },
  },
  computed: {},
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 50px;
      top: 10px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
    .nav {
      display: flex;
      justify-content: center;
      padding-top: 50px;
      font-size: 20px;
      a {
        text-decoration: none;
        color: #9b9ab3;

        &.active {
          color: #030303;
        }
      }
      span {
        padding: 0 5px;
      }
    }
    .content {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;
      .phonelogin {
        .row {
          display: flex;
          margin-bottom: 20px;
        }
        .ipt {
          outline: none;
          flex: 1;
          height: 48px;
          padding-left: 10px;
        }
        .btn {
          border: none;
          cursor: pointer;
          line-height: 48px;
          width: 80px;
        }
        .btncode {
          margin-left: 10px;
        }
        .btnlogin {
          width: 100%;
          background-color: #0a328e;
          color: #fff;
        }
      }
      #weixin {
        display: flex;
        justify-content: center;
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
